﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;

namespace KliveSigner
{
    [Activity(Label = "KliveSigner", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        int count = 1;
        private Button _buttonSign;
        private ProgressBar _progressBar;
        private System.Collections.ArrayList _tasks
            = new ArrayList();

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            _buttonSign = FindViewById<Button>(Resource.Id.MyButton);
            _progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);

            _buttonSign.Click += ButtonOnClick;
        }

        private void ButtonOnClick(object sender, EventArgs eventArgs)
        {
            _buttonSign.Enabled = false;
            _progressBar.Visibility = ViewStates.Visible;
            var tasks = new Task[10];
            for (int i = 0; i < tasks.Length; i++)
            {
                var t = Task.Factory.StartNew(SignInBackground);
                tasks[i] = t;
            }

            Task.Factory.StartNew(() =>
                                      {
                                          Task.WaitAll(tasks);
                                          RunOnUiThread(() =>
                                                            {
                                                                _progressBar.Visibility = ViewStates.Invisible;
                                                                _buttonSign.Enabled = true;

                                                            });

                                      });

        }

        private void SignInBackground()
        {
            var data = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"utf-8\" ?><xLive><token>002765348634475aba839a649f6fb194-1344687839</token><userId>2581812</userId></xLive>");
            try
            {

                var client = (HttpWebRequest)WebRequest.Create("http://point.wps.cn/kpoints/submit/sign/");
                client.ContentType = "application/x-www-form-urlencoded";
                client.Method = WebRequestMethods.Http.Post;
                client.KeepAlive = false;

                var stream = client.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();


                var response = client.GetResponse();
                var rs = response.GetResponseStream();
                var reader = new StreamReader(rs, Encoding.UTF8);
                var json = reader.ReadToEnd();
                var jobj = JObject.Parse(json);
                RunOnUiThread(() => DisplayResults(jobj));

            }
            catch (Exception ex)
            {
                RunOnUiThread(() => Toast.MakeText(this, ex.Message, ToastLength.Short).Show());
                Android.Util.Log.Error("klive", ex.ToString());
            }


        }

        private void DisplayResults(JObject jobj)
        {
            JToken state;
            var suc = jobj.TryGetValue("state", out state);
            if (suc)
            {
                var s = state.Value<int>();
                switch (s)
                {
                    case 1:
                        var str = string.Format("获得奖励{0}MB", jobj.Value<int>("rewardsize"));
                        var notification = new Notification(Resource.Drawable.Icon, str);
                        var intent = new Intent(this, typeof(Activity1));
                        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.CancelCurrent);
                        notification.SetLatestEventInfo(this, "签到", str, pendingIntent);
                        var nm = NotificationManager.FromContext(this);
                        nm.Notify(1, notification);
                        break;
                    case -102:
                        Toast.MakeText(this, "今天已经签过到了", ToastLength.Short).Show();
                        break;
                    case -2:
                        Toast.MakeText(this, "错误Token", ToastLength.Short).Show();
                        break;
                }

            }
        }
    }
}

